<template>
  <!-- 申购审批列表 -->
  <base-page-view class-name="purchase-list">
    <template v-if="pageLoaded">
      <view class="header">
        <tabs :tabs="tabList" :tab-index="tabIndex" @tabClick="tabClick" />
      </view>
      <view class="list">
        <template v-if="createOrderPermission">
          <view v-for="(gItem, gIndex) in list" :key="gIndex" class="item" @click="toDetail(gItem, 'purchase')">
            <view class="item-header">
              <view class="item-name">{{ gItem.goods_name }}</view>
              <view class="item-state" :class="'item-state'+gItem.status">{{ statusObj[gItem.status] }}</view>
            </view>
            <view class="item-content">
              <view class="line">
                <view class="label">申购数量</view>
                <view class="value">{{ gItem.goods_num }}箱</view>
              </view>
              <view v-if="false" class="line">
                <view class="label">当前库存</view>
                <view class="value">{{ gItem.goods_stock }}箱</view>
              </view>
              <view class="line">
                <view class="label">申购单号</view>
                <view class="value">{{ gItem.order_no }}</view>
              </view>
              <view class="line">
                <view class="label">申购时间</view>
                <view class="value">{{ (gItem.order_time * 1000) | formatDate }}</view>
              </view>
              <view v-if="gItem.status === 1" class="footer-line">
                <view class="money">{{ gItem.total | formatMoney }}</view>
                <view>
                  <!-- <view class="btn" @click.stop="toCancel(gIndex)">取消订单</view> -->
                  <view class="btn main" @click.stop="toPay(gIndex)">去付款</view>
                </view>
              </view>
            </view>
          </view>
        </template>
        <template v-else>
          <view v-for="(gItem, gIndex) in list" :key="gIndex" class="item" @click="toDetail(gItem)">
            <view class="item-header">
              <view class="item-name">{{ gItem.goods_name }}</view>
              <view class="item-state" :class="'item-state'+gItem.approval_status">{{ approvalObj[gItem.approval_status] }}</view>
            </view>
            <view class="item-content">
              <view class="line">
                <view class="label">申购数量</view>
                <view class="value">{{ gItem.goods_number }}箱</view>
              </view>
              <view class="line">
                <view class="label">申购单号</view>
                <view class="value">{{ gItem.apply_no }}</view>
              </view>
              <view class="line">
                <view class="label">申购时间</view>
                <view class="value">{{ (gItem.created_at * 1000) | formatDate }}</view>
              </view>
              <view class="line">
                <view class="label">审批人昵称</view>
                <view class="value">{{ gItem.approval_nickname }}</view>
              </view>
              <view class="line">
                <view class="label">审批人电话</view>
                <view class="value phone-value" @click.stop="$callPhone(gItem.approval_mobile)">
                  <view>{{ gItem.approval_mobile }}</view>
                  <b-image class-name="icon" src="/static/images/box/icon_phone.png" mode="aspectFit" :is-asset="true" />
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
      <base-list-state :list-length="listLength" :min-length="3" :list-query="{page_no: listQuery.page_no, page_size: listQuery.page_size}" :list-state="listState" :list-empty="listEmpty" />
    </template>
    <pay-dialog
      ref="payDialog"
      :order-no="order_no"
      :from-type="from_type"
      @submitCallBack="toPayResult"></pay-dialog>
    <confirm-popup ref="confirm"></confirm-popup>
  </base-page-view>
</template>
<script>
import confirmPopup from '@/components/confirmPopup/index'
import tabs from '../components/tabs/index'
import payDialog from '../components/payDialog'
import { debounce } from '@/utils/tools'
import './index.scss'

let queryKey = ''
let apiKey = ''
export default {
  components: {
    confirmPopup,
    tabs,
    payDialog
  },
  data() {
    return {
      pageLoaded: false,
      createOrderPermission: false,
      tabIndex: 0,
      statusObj: {
        '1': '待付款',
        '4': '已完成',
        '5': '已取消',
        '7': '已取消',
        '8': '已退款'
      },
      approvalObj: {
        '1': '待审批',
        '2': '申购通过',
        '3': '申购驳回',
        '4': '已撤销'
      },
      listQuery: {
        page_no: 1,
        page_size: 10
      },
      curent_page_no: 1, // 用来操作某条记录后更新数据
      list: [],
      listState: {
        loading: true,
        more: true
      },
      listEmpty: { type: 'empty_collect', text: '暂无相关订单信息' },
      order_no: '',
      from_type: 0
    }
  },
  computed: {
    tabList: function() {
      return this.createOrderPermission ? [
        { label: '所有', value: '' },
        { label: '待付款', value: 1 },
        { label: '已取消', value: 7 },
        { label: '已完成', value: 4 }
      ] : [
        { label: '所有', value: '' },
        { label: '待审批', value: 1 },
        { label: '申购通过', value: 2 },
        { label: '申购驳回', value: 3 },
        { label: '已撤销', value: 4 }
      ]
    },
    listLength: function() {
      return this.list.length
    }
  },
  onLoad(option) {
    this.createOrderPermission = this.userInfo && this.userInfo.boxPermission && this.userInfo.boxPermission.includes(2)
    queryKey = this.createOrderPermission ? 'order_status' : 'approval_status'
    apiKey = this.createOrderPermission ? 'getTopPurchase' : 'getPurchase'
    this.tabIndex = Number(option.tab || 0)
    this.listQuery[queryKey] = this.tabList[this.tabIndex].value
    this.fetchData()
  },
  onPullDownRefresh() {
    this.listQuery.page_no = 1
    this.fetchData(false)
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      this.listQuery.page_no++
      this.fetchData()
    }
  }, 500),
  methods: {
    tabClick(index) {
      this.tabIndex = index
      this.listQuery.page_no = 1
      this.listQuery[queryKey] = this.tabList[this.tabIndex].value
      this.list = []
      this.fetchData()
    },
    async fetchData(showLoading = true) {
      this.listState.loading = true
      const res = await this.$api.boxApi[apiKey]({ ...this.listQuery }, showLoading)
      if (res.success && res.data) {
        if (this.listQuery.page_no === 1) {
          this.list = []
        }
        const list = (res.data || []).map(i => {
          return this.createOrderPermission ? {
            ...i,
            goods_name: i.shopping_items.item_list && i.shopping_items.item_list.length ? i.shopping_items.item_list[0].title : '',
            goods_stock: i.shopping_items.item_list && i.shopping_items.item_list.length ? i.shopping_items.item_list[0].stock_number : 0
          } : {
            ...i,
            goods_name: i.box_apply_goods_d_t_o_s && i.box_apply_goods_d_t_o_s.length ? i.box_apply_goods_d_t_o_s[0].goods_name : '',
            goods_number: i.box_apply_goods_d_t_o_s && i.box_apply_goods_d_t_o_s.length ? i.box_apply_goods_d_t_o_s[0].goods_number : 0
          }
        })
        this.list = this.list.concat(list)
        this.listState.more = list.length === this.listQuery.page_size
      }
      setTimeout(() => {
        this.listState.loading = false
        uni.stopPullDownRefresh()
      }, 500)
      this.pageLoaded = true
    },
    updateList() {
      this.list.slice((this.curent_page_no - 1) * this.listQuery.page_size, this.list.length)
      this.listQuery.page_no = this.curent_page_no
      this.fetchData()
    },
    toCancel(gIndex) {
      const item = this.list[gIndex]
      this.current_page_no = Math.floor(gIndex / this.listQuery.page_size) + 1
      this.$refs.confirm.show({
        title: '提示',
        content: '是否取消订单',
        yesCb: async() => {
          const res = await this.$api.orderApi.orderCancel({
            order_no: item.order_no
          })

          if (res.success) {
            this.updateList()
            uni.showToast({
              title: '取消成功',
              icon: 'none',
              duration: 2000,
              mask: true
            })
          }
        }
      })
    },
    toPay(gIndex) {
      const item = this.list[gIndex]
      this.current_page_no = Math.floor(gIndex / this.listQuery.page_size) + 1
      this.order_no = item.order_no
      this.from_type = item.shopping_items && item.shopping_items.item_list && item.shopping_items.item_list.length ? item.shopping_items.item_list[0].from_type : 0
      this.$refs.payDialog.show()
    },
    toDetail(item, type) {
      if (type === 'purchase') {
        this.$navigateTo(`/pagesBox/pick-up-detail/index?orderNo=${item.order_no}&boxType=buy`)
      } else {
        this.$navigateTo(`/pagesBox/approval/detail?id=${item.id}&type=purchase`)
      }
    },
    // 支付结果
    toPayResult(res) {
      // res = {
      //   data: {
      //     errMsg: 'requestPayment:ok'
      //   },
      //   type: 1
      // }
      this.updateList()
    }
  }
}
</script>
